package com.ourhealth.controller;

import com.alibaba.dubbo.common.utils.Assert;
import com.aliyuncs.exceptions.ClientException;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.ourhealth.constant.MessageConstant;
import com.ourhealth.constant.RedisMessageConstant;
import com.ourhealth.entity.Result;
import com.ourhealth.utils.SMSUtils;
import com.ourhealth.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

@RestController
@RequestMapping("validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @RequestMapping("send4Order")
    public Result send4Order(@RequestParam("telephone") String telephone){
        Jedis resource = null;
        try {
            String s = ValidateCodeUtils.generateValidateCode4String(4);
            SMSUtils.sendShortMessage("SMS_178466566",telephone,s);
            resource = jedisPool.getResource();
            resource.setex(telephone + RedisMessageConstant.SENDTYPE_ORDER,5 * 600,s.toString());
        } catch (ClientException e) {
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        } finally {
            resource.close();
        }
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    @RequestMapping("/code/{deviceId}")
    public void createCode(@PathVariable String deviceId, HttpServletResponse response) throws Exception {
        Assert.notNull(deviceId, "机器码不能为空");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = defaultKaptcha.createText();
        //生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        //生成的验证码写入redis
        Jedis resource = jedisPool.getResource();
        resource.setex(deviceId,600*5,text);
        resource.close();
        //获取输出流
        ServletOutputStream out = response.getOutputStream();
        //将图片写回浏览器
        ImageIO.write(image, "JPEG", out);
    }
}
